{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>智能体管理 - 数据源管理系统</title>
    {% csrf_token %}
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" />
    <style>
      .sidebar {
        height: 100vh;
        background-color: #343a40;
        color: white;
        padding-top: 20px;
      }
      .sidebar .nav-link {
        color: #adb5bd;
        border-radius: 0;
      }
      .sidebar .nav-link.active {
        background-color: #0d6efd;
        color: white;
      }
      .content {
        padding: 20px;
      }
      .card-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid rgba(0, 0, 0, 0.125);
      }
      .agent-card {
        margin-bottom: 20px;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      }
      .agent-header {
        background: linear-gradient(135deg, #0d6efd, #0b5ed7);
        color: white;
        padding: 15px;
      }
      .agent-body {
        padding: 15px;
      }
      .btn-primary {
        background-color: #0d6efd;
        border-color: #0d6efd;
      }
    </style>
  </head>
  <body>
    <div class="container-fluid">
      <div class="row">
        <!-- 侧边栏 -->
        <div class="col-md-2 d-none d-md-block sidebar">
          <div class="text-center mb-4">
            <h3>数据管理</h3>
          </div>
          <ul class="nav flex-column">
            <li class="nav-item">
              <a class="nav-link" href="{% url 'datasource_list' %}">
                <i class="bi bi-database me-2"></i>
                数据源管理
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link active" href="{% url 'agent_management' %}">
                <i class="bi bi-robot me-2"></i>
                智能体管理
              </a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{% url 'operation_log' %}">
                <i class="bi bi-clock-history me-2"></i>
                操作日志
              </a>
            </li>
          </ul>
        </div>

        <!-- 主内容区 -->
        <main class="col-md-10 ms-sm-auto px-md-4 content">
          <!-- 顶部导航 -->
          <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
            <div class="container-fluid">
              <h4 class="mb-0">智能体管理</h4>
              <div class="d-flex ms-auto gap-2">
                <a href="{% url 'agent_form' %}" class="btn btn-primary">
                  <i class="bi bi-plus-circle me-1"></i>
                  新建智能体
                </a>
                <button class="btn btn-outline-secondary">
                  <i class="bi bi-person me-1"></i>
                  登录
                </button>
              </div>
            </div>
          </nav>

          <!-- 智能体列表 -->
          <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">智能体列表</h5>
              <div class="input-group" style="width: 300px">
                <input type="text" class="form-control" placeholder="搜索智能体..." />
                <button class="btn btn-outline-secondary" type="button">
                  <i class="bi bi-search"></i>
                </button>
              </div>
            </div>
            <div class="card-body">
              <!-- 智能体卡片列表 -->
              <div class="row" id="agentList">
                {% for agent in agents %}
                <div class="col-md-4">
                  <div class="agent-card border">
                    <div class="agent-header d-flex justify-content-between align-items-center">
                      <h6>{{ agent.name }}</h6>
                      <span class="badge {% if agent.is_active %}bg-success{% else %}bg-secondary{% endif %}">{% if agent.is_active %}运行中{% else %}已停止{% endif %}</span>
                    </div>
                    <div class="agent-body">
                      <p class="mb-2">
                        <strong>描述:</strong>
                        {{ agent.description|default:"无描述" }}
                      </p>
                      <p class="mb-2">
                        <strong>数据源:</strong>
                        {{ agent.datasource.name }}
                      </p>
                      <p class="mb-2">
                        <strong>状态:</strong>
                        <span class="{% if agent.is_active %}text-success{% else %}text-secondary{% endif %}">{% if agent.is_active %}正常运行{% else %}已停止{% endif %}</span>
                      </p>
                      <p class="mb-2">
                        <strong>最后运行时间:</strong>
                        {% if agent.last_run_time %}{{ agent.last_run_time|date:"Y-m-d H:i:s" }}{% else %}从未运行{% endif %}
                      </p>
                      <div class="d-flex justify-content-between mt-3">
                        <a href="{% url 'agent_form' agent.pk %}" class="btn btn-primary btn-sm">配置</a>
                        {% if agent.execution_type == 'manual' %}
                        <button class="btn btn-success btn-sm me-2" onclick="runAgent({{ agent.pk }})">执行</button>
                        {% endif %}
                        <button class="btn btn-outline-secondary btn-sm">查看日志</button>
                      </div>
                    </div>
                  </div>
                </div>
                {% empty %}
                <div class="col-12">
                  <div class="text-center py-5">
                    <i class="bi bi-robot" style="font-size: 3rem; color: #ccc"></i>
                    <h5 class="mt-3 text-muted">暂无智能体</h5>
                    <p class="text-muted">点击"新建智能体"按钮创建您的第一个智能体</p>
                    <a href="{% url 'agent_form' %}" class="btn btn-primary mt-2">
                      <i class="bi bi-plus-circle me-1"></i>
                      新建智能体
                    </a>
                  </div>
                </div>
                {% endfor %}
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      // 页面加载完成后执行
      document.addEventListener('DOMContentLoaded', function() {
        // 检查CSRF令牌是否存在
        const csrftoken = getCookie('csrftoken');
        console.log('CSRF Token:', csrftoken);
        if (!csrftoken) {
          console.error('CSRF Token not found in cookies');
        }
      });

      function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
          const cookies = document.cookie.split(';');
          for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // 检查cookie是否以name开头
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
              cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
              break;
            }
          }
        }
        return cookieValue;
      }

      function runAgent(agentId) {
        // 显示确认对话框
        if (confirm('确定要执行这个智能体吗？')) {
          // 获取CSRF令牌
          const csrftoken = getCookie('csrftoken');

          if (!csrftoken) {
            alert('CSRF令牌缺失，无法执行操作');
            console.error('CSRF Token not found in cookies');
            return;
          }

          console.log('Sending request with CSRF Token:', csrftoken);

          // 发送POST请求到服务器执行智能体
          axios.post(`/agent/run/${agentId}/`, {}, {
            headers: {
              'X-CSRFToken': csrftoken,
              'Content-Type': 'application/json'
            }
          })
            .then(function (response) {
              // 处理成功响应
              alert('智能体执行成功！');
              // 刷新页面或更新智能体状态
              location.reload();
            })
            .catch(function (error) {
              // 处理错误响应
              let errorMessage = '智能体执行失败';
              if (error.response && error.response.data && error.response.data.message) {
                errorMessage += ': ' + error.response.data.message;
              } else if (error.message) {
                errorMessage += ': ' + error.message;
              }
              alert(errorMessage);
            });
        }
      }
    </script>
  </body>
</html>
